<template>
    <div class="app-container">
        <span style="font-size: 26px;margin-right: 100px;">生产者补贴</span>
        <!-- @click="saveInfo" -->
        <el-button v-if="!formDisabled" type="primary" size="medium" :loading="saveLoading" @click="saveForm">保存</el-button>
        <el-button v-if="!formDisabled && !abnormalDisabled" type="primary" plain size="medium" :loading="submitLoading"
            @click="submitForm">下一个</el-button>
        <el-button v-if="formDisabled" disabled type="info" size="medium">审核中</el-button>


        <el-form :disabled="formDisabled" ref="elForm" :model="form" :rules="rules" size="medium" label-width="130px"
            label-position="left">
            <div class="card-container">
                <el-card class="infoDiv">
                    <span class="corner-label">基本信息</span>

                    <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="12">
                            <el-form-item label="身份证号码" prop="idCard">
                                <el-input v-model="form.idCard" placeholder="请输入身份证号码" :maxlength="18" clearable
                                    @input="calculateAgeFromIdCard" @blur="syncHistory"
                                    :style="{ width: '100%' }"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="申请人" prop="appyBy">
                                <el-input v-model="form.appyBy" placeholder="请填写姓名" clearable :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="6">
                            <el-form-item label="性别" prop="sex" label-width="60px">
                                <el-select v-model="form.sex" placeholder="请选择性别" clearable :style="{ width: '100%' }">
                                    <el-option v-for='item in sexOptions' :label="item.label" :key="item.value"
                                        :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="年龄" prop="age" label-width="60px">
                                <el-input v-model="form.age" placeholder="输入年龄" clearable
                                    :style="{ width: '100%' }"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="身份证地址" prop="idCardAddr">
                                <el-input v-model="form.idCardAddr" placeholder="请输入身份证地址" clearable
                                    @blur="syncOftenAddrIfNotModified" :style="{ width: '100%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="12">
                            <el-form-item label="现住地址" prop="oftenAddr">
                                <el-input v-model="form.oftenAddr" placeholder="请输入现住地址" clearable
                                    :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="联系方式" prop="phone">
                                <el-input v-model="form.phone" placeholder="请输入联系方式" :maxlength="11" clearable
                                    :style="{ width: '100%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="12">
                            <el-form-item label="一卡通账号" prop="bankCard">
                                <el-input v-model="form.bankCard" placeholder="请输入一卡通账号" show-word-limit clearable
                                    :style="{ width: '100%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
            </div>
            <div class="card-container">
                <el-card class="infoDiv">
                    <span class="corner-label">补贴类型</span>
                    <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="12">
                            <el-form-item label="玉米种植补贴面积" prop="yumiareaAmount">
                                <el-input v-model="form.yumiareaAmount" placeholder="请输入申报土地面积" type="number" clearable
                                    :style="{ width: '100%' }">
                                    <template slot="append">亩</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :style="{ width: '100%' }"></el-col>
                    </el-row>
                    <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="12">
                            <el-form-item label="大豆种植补贴面积" prop="dadouareaAmount">
                                <el-input v-model="form.dadouareaAmount" placeholder="请输入申报土地面积" type="number" clearable
                                    :style="{ width: '100%' }">
                                    <template slot="append">亩</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :style="{ width: '100%' }"></el-col>
                    </el-row>
                    <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="4">
                            <el-form-item label="稻谷种植补贴面积" prop="areaAmount">
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="地表水" prop="daogudibiareaAmount" label-width="60px">
                                <el-input v-model="form.daogudibiareaAmount" clearable type="number"
                                    :style="{ width: '100%' }">
                                    <template slot="append">亩</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="地下水" prop="daogudixiaareaAmount" label-width="60px">
                                <el-input v-model="form.daogudixiaareaAmount" clearable type="number"
                                    :style="{ width: '100%' }">
                                    <template slot="append">亩</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="合计" prop="daoguheareaAmount" label-width="40px">
                                <el-input :disabled="true" v-model="form.daoguheareaAmount" clearable type="number"
                                    :style="{ width: '100%' }">
                                    <template slot="append">亩</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item label="合计种植补贴面积" prop="areaAmount">
                                <el-input :disabled="true" v-model="form.areaAmount" type="number"
                                    :style="{ width: '50%' }">
                                    <template slot="append">亩</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item label="备注" prop="remark">
                                <el-input v-model="form.remark" type="textarea" placeholder=""
                                    :autosize="{ minRows: 1, maxRows: 4 }" :style="{ width: '100%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
            </div>
            <!-- 对于异常情况，驳回理由的显示 -->
            <div class="card-container" v-if="abnormalDisabled">
                <el-card class="infoDiv">
                    <span class="corner-label" style="background-color:rgb(234, 183, 225)">驳回理由</span>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="驳回理由" prop="abnormal" label-width="80px">
                                <el-input v-model="form.abnormal" type="textarea" :disabled="true"
                                    :autosize="{ minRows: 4, maxRows: 8 }" :style="{ width: '100%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
            </div>

            <!-- 上级干部对信息的审核通过与拒绝 -->
            <!-- <div class="card-container">
                <el-card class="infoDiv">
                    <span class="corner-label" style="background-color:rgb(234, 183, 225)">驳回理由</span>
                    <el-row :gutter="24">
                        <el-col :span="24">
                            <el-form-item>
                                <el-button @click="approveApply">通过申请</el-button>
                                <el-button @click="rejectApply">驳回申请</el-button>
                            </el-form-item>

                        </el-col>
                    </el-row>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="驳回理由" prop="abnormal" label-width="80px">
                                <el-input v-model="form.abnormal" type="textarea" placeholder="请输入驳回理由"
                                    :disabled="isDisabled" :autosize="{ minRows: 4, maxRows: 8 }"
                                    :style="{ width: '100%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
            </div> -->
        </el-form>
    </div>
</template>
  
<script>
import { queryhistoryOne, addProduce, updateProduce, submitProduce, getProduceByappNum, getProduceById, rejectProduce } from "@/api/agriculture/agriculture";

export default {
    name: "Produce",
    data() {
        return {
            // 按钮loading
            saveLoading: false,
            submitLoading: false,
            formDisabled: false, //控制整个表格是否输入，false表示可以输入
            abnormalDisabled: false, //控制驳回表格是否显示
            rejectDisabled: false, //控制审批窗口是否显示
            isDisabled: true, //控制审批窗口中的驳回理由是否显示
            villageName: undefined,
            townName: undefined,
            hasUserModifiedOftenAddr: false,

            form: {
                appyBy: undefined,
                sex: undefined,
                age: undefined,
                idCard: undefined,
                idCardAddr: undefined,
                oftenAddr: undefined,
                phone: undefined,
                bankCard: undefined,
                appType: '生产者补贴',
                yumiareaAmount: 0,     // 玉米
                dadouareaAmount: 0,    // 大豆
                daogudibiareaAmount: 0, // 稻谷-地表水
                daogudixiaareaAmount: 0, // 稻谷-地下水
                daoguheareaAmount: 0,   // 稻谷-合计（自动计算）
                areaAmount: 0,   // 总合计（自动计算）
                remark: undefined,
                abnormal: undefined,
                status: '待处理',
                nodeName: '',
                villageName: '',
                submitBy: '',
                year: new Date().getFullYear(),
            },
            rules: {
                appyBy: [{
                    required: true,
                    message: '请输入申请人',
                    trigger: 'blur'
                }],
                sex: [{
                    required: true,
                    message: '请选择性别',
                    trigger: 'change'
                }],
                age: [{
                    required: true,
                    message: '请输入年龄',
                    trigger: 'blur'
                }],
                idCard: [{
                    required: true,
                    message: '请输入身份证号码',
                    trigger: 'blur'
                }, {
                    pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
                    message: '请输入正确的身份证号',
                    trigger: 'blur'
                }],
                idCardAddr: [{
                    required: true,
                    message: '请输入身份证地址',
                    trigger: 'blur'
                }],
                oftenAddr: [{
                    required: true,
                    message: '请输入现住地址',
                    trigger: 'blur'
                }],
                phone: [{
                    required: true,
                    message: '请输入联系方式',
                    trigger: 'blur'
                }, {
                    pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                    message: '请输入正确的手机号',
                    trigger: 'blur'
                }],
                bankCard: [{
                    required: true,
                    message: '请输入一卡通账号',
                    trigger: 'blur'
                }],
                remark: [],
            },
            sexOptions: [{
                "label": "男",
                "value": "男"
            }, {
                "label": "女",
                "value": "女"
            }]
        }
    },

    created() {
        // console.log("目前登录的角色是", this.$store.state.user.name, this.$store.state.user.roles, this.$store.state.user.permissions)
        // this.user = this.$store.state.user
        // this.userName = this.$store.state.user.name;
        this.villageName = this.$store.state.user.user.villageName;
        console.log("当前村名1", this.villageName)
        console.log("当前村名2", this.$store.state.user.roles[0])
        // this.townName = this.$store.state.user.user.townName

        if (this.$store.state.user.roles[0] == 'village') {  // 为村干部时
            this.form.nodeName = this.villageName
            this.form.villageName = this.villageName
            this.form.submitBy = this.villageName
            // this.form.townName = this.townName
            console.log("表格中的村名", this.form.villageName)
        }
        const id = this.$route.params && this.$route.params.id;
        console.log("查询工单编号4", id)
        if (id) {
            console.log("查询工单编号3", id)
            getProduceById(id).then(response => {
                console.log("查询信息", response)
                this.form = response.data;
                if (this.form.node > 1) {
                    this.formDisabled = 'true'
                }
                if (this.form.node == 1 && this.form.status == '异常') {
                    this.abnormalDisabled = 'true'
                }
            });
        }
    },
    computed: {
        // 1. 计算稻谷合计：地表水 + 地下水
        computedDaoguTotal() {
            const surface = this.form.daogudibiareaAmount;
            const groundwater = this.form.daogudixiaareaAmount;
            var m = Math.pow(100, 2);
            const hehe = (surface * m + groundwater * m) / m;
            return hehe;
        },

        // 2. 计算总合计：玉米 + 大豆 + 稻谷合计
        computedTotalArea() {
            const yumi = this.form.yumiareaAmount;
            const dadou = this.form.dadouareaAmount;
            const daogu = this.computedDaoguTotal;
            var m = Math.pow(100, 2);
            const hehe = (yumi * m + dadou * m + daogu * m) / m;
            return hehe;
        }
    },
    watch: {
        // 监听计算结果，同步回 form（用于显示）
        computedDaoguTotal(newVal) {
            this.form.daoguheareaAmount = newVal;
        },
        computedTotalArea(newVal) {
            this.form.areaAmount = newVal;
        },
        'form.oftenAddr'(newValue, oldValue) {
            // 注意：要防止初始同步或 blur 同步触发此 watcher 时错误地设置标记
            // 我们只关心用户主动输入导致的变化
            if (oldValue !== undefined && newValue !== oldValue) {
                // 用户修改了现住地址，标记为已自定义
                this.hasUserModifiedOftenAddr = true;
            }
        },
        '$route'(to, from) {
            const id = to.params.id;
            if (id) {
                this.fetchData(id);
            }
        }
    },

    mounted() {
        // 初始化一次
        this.form.daoguheareaAmount = this.computedDaoguTotal;
        this.form.areaAmount = this.computedTotalArea;
    },

    methods: {
        fetchData(id) {
            console.log("查询工单编号:", id);
            getProduceById(id).then(response => {
                this.form = response.data;
                if (this.form.node > 1) {
                    this.formDisabled = 'true';
                }
                if (this.form.node === 1 && this.form.status === '异常') {
                    this.abnormalDisabled = 'true';
                }
            });
        },
        syncOftenAddrIfNotModified() {
            const idCardAddr = this.form.idCardAddr.trim();
            // 只有在用户没有手动修改过 oftenAddr 的情况下才进行同步
            if (!this.hasUserModifiedOftenAddr && idCardAddr) {
                this.form.oftenAddr = idCardAddr;
            }
            // 如果身份证地址为空，也可以选择清空 oftenAddr（可选）
            // else if (!this.hasUserModifiedOftenAddr) {
            //   this.form.oftenAddr = '';
            // }
        },
        syncHistory() {
            const idCard = this.form.idCard;
            queryhistoryOne({ idCard: idCard }).then(res => {
                console.log("历史信息", res);
                if (res.idCard) {
                    this.form.appyBy = res.appyBy;
                    this.form.sex = res.sex;
                    this.form.phone = res.phone;
                    this.form.idCardAddr = res.idCardAddr;
                    this.form.oftenAddr = res.oftenAddr;
                    this.form.bankCard = res.bankCard;
                }

            })
        },
        calculateAgeFromIdCard() {
            const idCard = this.form.idCard.trim();
            // 清空年龄（如果身份证无效或未填满18位）
            if (!idCard || idCard.length !== 18) {
                this.form.age = '';
                return;
            }
            // 验证身份证号码格式（简单校验）
            const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
            if (!idCardRegex.test(idCard)) {
                this.form.age = '';
                return;
            }
            // 提取出生年份（身份证第7-10位）
            const birthYear = parseInt(idCard.substring(6, 10));
            // 获取当前年份
            const currentYear = new Date().getFullYear();
            // 计算年龄：当前年份 - 出生年份
            // （不考虑今年生日是否已过）
            const age = currentYear - birthYear;
            // 设置年龄
            this.form.age = age.toString();
        },
        // approveApply() {
        //     this.isDisabled = true; // 切换审核 驳回理由禁用状态 
        // },
        // rejectApply() {
        //     this.isDisabled = false; // 切换审核 驳回理由使用状态 
        // },

        getFormattedDateTime() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需+1
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        saveForm: function () {
            this.$refs['elForm'].validate(valid => {
                if (valid) {
                    if (this.form.id) {
                        this.saveLoading = true;
                        this.form.status = "待处理";
                        updateProduce(this.form).then(response => {
                            this.$modal.msgSuccess("修改数据成功");
                        }).finally(() => {
                            this.$router.push("/agricultureProcess");
                            this.saveLoading = false;
                            this.resetForm();
                        });
                    } else {
                        this.saveLoading = true;
                        console.log("传入的村名", this.form.villageName)
                        addProduce(this.form).then(response => {
                            this.$modal.msgSuccess("保存成功");
                        }).finally(() => {
                            this.$router.push("/agricultureProcess");
                            this.saveLoading = false;
                            this.resetForm();
                        });
                    }
                }
            })
        },
        submitForm: function () {
            this.$refs['elForm'].validate(valid => {
                if (valid) {
                    if (this.form.id) {
                        this.submitLoading = true;
                        this.form.status = "待处理";
                        updateProduce(this.form).then(response => {
                            this.$modal.msgSuccess("修改数据成功");
                        }).finally(() => {
                            this.submitLoading = false;
                            this.resetForm();
                        });
                    } else {
                        this.submitLoading = true;
                        addProduce(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                        }).finally(() => {
                            this.submitLoading = false;
                            this.resetForm();
                        });
                    }

                }
            })
        },

        resetForm() {
            this.$refs['elForm'].resetFields()
        },
    }
}
</script>
<style scoped>
.app-container {
    width: 80%;
    align-items: center;
    margin-left: 10%;

    /* border: 1px solid rgb(204, 28, 28); */
}

.card-container {
    position: relative;
}

.infoDiv {
    width: 100%;
    align-items: center;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-top: 20px;
    padding-top: 20px;
}

.corner-label {
    position: absolute;
    top: 0;
    left: 0;
    background: #81B337;
    /* 背景色 */
    color: white;
    /* 文字颜色 */
    padding: 2px 8px;
    /* 内边距 */
    font-size: 20px;
    /* 字体大小 */
    border-radius: 4px;
    /* 圆角，左上角和右下角有圆角（根据需求调整） */
    transform: translate(-10%, -10%);
    /* 微调位置，使其覆盖在圆角上 */
    /* 如果需要，可以设置z-index */
    z-index: 1;
}
</style>